package common

import (
	clientv3 "go.etcd.io/etcd/client/v3"
	"log"
	"strconv"
	"time"
)

/*
*
将服务注册到ETCD
*/
func InitETCD(name, ip string, port int, weight string) *clientv3.Client {

	// 创建etcd客户端
	cli, err := clientv3.New(clientv3.Config{
		Endpoints: []string{"localhost:2379"},
		//DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatal(err)
	}
	//defer cli.Close()

	// 创建注册中心实例
	registry := NewEtcdRegistry(cli, 10) // 10秒TTL

	// 注册服务实例
	instance := &ServiceInstance{
		ID:      ip + ":" + strconv.Itoa(port),
		Name:    name,
		Address: ip,
		Port:    port,
		Metadata: map[string]string{
			"weight": weight,
		},
	}

	if err := registry.Register(instance); err != nil {
		log.Fatal(err)
	}

	log.Println("服务:" + name + "注册成功")
	return cli

	// 保持运行
	//select {}
}

/*
*
根据服务名称从ETCD中获取服务示例
*/
func GetEtcdServer(name string) (ip, port string) {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()

	discovery := NewDiscovery(cli)

	// 监听user-service
	if err := discovery.WatchService(name); err != nil {
		log.Fatal(err)
	}

	// 获取服务实例
	for {
		instances, err := discovery.GetInstances(name)
		if err != nil {
			log.Println(err)
		} else {
			log.Printf("当前实例: %+v\n", instances)
			return instances[0].Address, strconv.Itoa(instances[0].Port)
		}
		time.Sleep(5 * time.Second)
	}
}
